import logging

from django.db import DatabaseError
from redis.exceptions import RedisError

# 获取配置中定义的logger，用来记录日志
logger = logging.getLogger('django')

# TODO: 用ninja重写mysql和redis异常处理的方法，未测试过哪种能生效


# 方式一：
# api = NinjaExtraAPI()
from meiduo_mall.apis import api


# GROK改进
class DatabaseRedisException(Exception):
    """自定义数据库Redis异常类"""
    pass


@api.exception_handler(DatabaseRedisException)
def database_redis_exception(request, exc):
    """处理DatabaseRedisException异常"""
    # 检查异常是否存在并属于特定类型
    if exc is not None:  # 确保exc不是None
        if isinstance(exc, (DatabaseError, RedisError)):  # 使用元组检查多个类型
            logger.error('[%s] %s' % (request, exc))  # 记录错误日志
            return api.create_response(
                request,
                {'message': '服务器内部错误'},
                status=507,  # 存储空间不足状态码（可考虑改为500）
            )

    # 回退到默认异常处理器，传递exc参数
    return api.exception_handler(request, exc)


api.register_controllers(DatabaseRedisException)

# 文档代码
# from ninja_extra.exceptions import APIException
# from ninja_extra import api_controller, route, NinjaExtraAPI, status
# from ninja import constants
#
#
# class CustomAPIException(APIException):
#     status_code = status.HTTP_401_UNAUTHORIZED
#     default_detail = 'UnAuthorized'
#
#
# @api_controller('', tags=['My Operations'], auth=constants.NOT_SET, permissions=[])
# class MyController:
#     @route.get('/exception')
#     def custom_exception(self):
#         raise CustomAPIException()
#
#
# api = NinjaExtraAPI(title='Exception Test')
# api.register_controllers(MyController)


# KIMI.AI修正
# from ninja_extra import NinjaExtraAPI, api_controller, route
# from ninja_extra.exceptions import APIException
# from ninja_extra.controllers import ControllerBase
# from ninja_extra import status
# import logging
#
# # 定义自定义异常
# class DatabaseRedisException(Exception):
#     pass
#
# # 定义异常处理器
# @api.exception_handler(DatabaseRedisException)
# def database_redis_exception(request, exc):
#     logger = logging.getLogger(__name__)
#     logger.error(f"[{request}] {exc}")
#     return api.create_response(
#         request,
#         {"message": "服务器内部错误"},
#         status=status.HTTP_500_INTERNAL_SERVER_ERROR,
#     )
#
# # 创建 API 实例
# api = NinjaExtraAPI(title="Exception Test")
#
# # 示例控制器
# @api_controller('', tags=['My Operations'], auth=None, permissions=[])
# class MyController(ControllerBase):
#     @route.get('/redis-exception')
#     def trigger_redis_exception(self):
#         raise DatabaseRedisException("Redis connection failed")
#
# # 注册控制器
# api.register_controllers(MyController)
